<?php
	// -----------   Page Vars    ----------
	$to_root = '';
	$authorized = array(0, 1);

	$menu_selected = 1;
	
	//  ---- init
	include($to_root.'_classes/init.php');
	
	$main = new ViewDescriptor('main');
	Template::addBreadcrumb('home.php', 'Home');
	
	/* ========   INSERT CODE HERE   ======== */
//print_r($_POST);
	
	if(isset($_POST['action']) && $_POST['action']=='new' &&																//---------    new Project
		isset($_POST['title'])&&
		isset($_POST['text'])){
			
		$title = ($_POST['title']);
		$text = ($_POST['text']);
		
		$bool = !isset($_POST['private']);
		
		$newid = $GLOBALS['Db-I']->newProject($title, $text, $bool);

		if(!is_array($newid)){
			if(isset($_POST['private'])) header('Location: todos.php?&action=edit&msg=insert_success');
			else header('Location: projects.php?id='.$newid.'&msg=insert_success');
		} else {
			if(isset($newid['Error']) && $newid['Error'] == ERROR_NOT_ALLOWED){
				header('Location: projects.php?msg=not_authorized');
			} else {
				header('Location: projects.php?msg=insert_error');
			}
		}
	} else if(isset($_POST['action']) && $_POST['action']=='edit' &&																//---------    edit Project
		isset($_POST['title'])&&
		isset($_POST['text']) && 
		isset($_POST['id'])){
					
		$newid = $GLOBALS['Db-I']->editProject($_POST['id'], $_POST['title'], $_POST['text']);
		if(!is_array($newid)){
			if(isset($_POST['lID'])) header('Location: todos.php?msg=update_success');//projects.php?lId='.$newid.'&action=edit&msg=insert_success');
			else header('Location: projects.php?id='.$newid.'&msg=update_success');
		} else {
			if(isset($newid['Error']) && $newid['Error'] == ERROR_NOT_ALLOWED){
				header('Location: projects.php?msg=not_authorized');
			} else {
				header('Location: projects.php?msg=update_error');
			}
		}
	} else if(isset($_GET['action']) && $_GET['action']=='delete' && (isset($_GET['id']) || isset($_GET['lId']))){										//---------    delete Project
		$id = (isset($_GET['id'])) ? $_GET['id']: $_GET['lId'];
		$newid = $GLOBALS['Db-I']->deleteProject($id);
		if(!is_array($newid)){
			if(isset($_GET['id'])) header('Location: projects.php?msg=delete_success');
			else header('Location: todos.php?msg=delete_success');
		} else {
			if(isset($newid['Error']) && $newid['Error'] == ERROR_NOT_ALLOWED){
				header('Location: project.php?msg=not_authorized');
			} else {
				header('Location: project.php?msg=delete_error');
			}
		}	
	} else if(isset($_GET['action']) && $_GET['action']=='share' && isset($_GET['lId'])){
		$newid = $GLOBALS['Db-I']->shareList($_GET['lId']);
		if(!is_array($newid)){
			header('Location: projects.php?pId='.$_GET['lId'].'&msg=share_success');
		} else {
			if(isset($newid['Error']) && $newid['Error'] == ERROR_NOT_ALLOWED){
				header('Location: project.php?lId='.$_GET['lId'].'&msg=not_authorized');
			} else {
				header('Location: project.php?lId='.$_GET['lId'].'&msg=share_error');
			}
		}	
	} else if(isset($_GET['action']) && $_GET['action']=='unshare' && isset($_GET['pId'])){
		$newid = $GLOBALS['Db-I']->unshareList($_GET['pId']);
		if(!is_array($newid)){
			header('Location: projects.php?lId='.$_GET['pId'].'&msg=unshare_success');
		} else {
			if(isset($newid['Error']) && $newid['Error'] == ERROR_NOT_ALLOWED){
				header('Location: project.php?pId='.$_GET['pId'].'&msg=not_authorized');
			} else {
				header('Location: project.php?pId='.$_GET['pId'].'&msg=unshare_error');
			}
		}	
	}
	
	if(((isset($_GET['id']) && $_GET['id']!= '') || (isset($_GET['lId']) && $_GET['lId']!= ''))  && !isset($_GET['action'])){   					//-------  view List/Project
		
		$id = (isset($_GET['id'])) ? $_GET['id'] : -1;
		$id = (isset($_GET['lId'])) ? $_GET['lId'] : $id;
	
		$content = new ViewDescriptor('content/projects_view');
		$project = $GLOBALS['Db-I']->getProject(($id));
		
		if(is_array($project) && isset($project['Error'])){
			if($project['Error'] == ERROR_NOT_ALLOWED) {
				header('Location: projects.php?msg=not_authorized');
				break;
			} else if($project['Error'] == ERROR_LIST_DOES_NOT_EXIST){
				header('Location: todos.php?msg='.$_GET['msg']);
				break;
			}
		} 
		//print_r($project);
		//User
		$u = new SubViewDescriptor('user');
		$u->addValue('id', $project->getOwner()->getId());
		$u->addValue('name', $project->getOwner()->getName());
		$u->addValue('pId', $project->getId());
		$u->removeSubView('ersteller');
		$u->addValue('extra', '(Ersteller)');
		$content->addSubView($u);
		unset($u);
		
		if($_SESSION['User']['id'] == $project->getOwner()->getId() || $_SESSION['User']['group']=='admin'){
			$a = new SubViewDescriptor('authorized');
			$a1 = new SubViewDescriptor('authorized1');
			$a2 = new SubViewDescriptor('authorized2');
			
			$a->addValue('id', $project->getId());
			$a1->addValue('id', $project->getId());
			$a2->addValue('id', $project->getId());
			
			$content->addSubView($a);
			$content->addSubView($a1);
			$content->addSubView($a2);
		} else {
			$content->removeSubView('authorized');
			$content->removeSubView('authorized1');
			$content->removeSubView('authorized2');
		}
		
		$project->loadUsers();
		$u = $project->getUsers();
		if(count($u)>0){
			foreach($u as $p){
				if(!is_array($p)){
					$p_s = new SubViewDescriptor('user');
					
					//ersteller adden
					$uu = new SubViewDescriptor('ersteller');
					$uu->addValue('id', $p->getId());
					$uu->addValue('pId', $project->getId());
					$p_s->addSubView($uu);
					unset($uu);
					
					$p_s->addValue('id', $p->getId());
					$p_s->addValue('name', $p->getName());
					$p_s->addValue('extra', '');
					$p_s->addValue('pId', $project->getId());
					$content->addSubView($p_s);
					unset($p_s);
				}
			}
		}
		
		if(isset($_GET['id'])) { //--------- Breadcrumbs for Project or Todo (depends on Referrer)
			Template::addBreadcrumb('projects.php', 'Projekte');
			Template::addBreadcrumb('projects.php?id='.$id, Template::cutString($project->getTitle(), 20));		
		} else if(isset($_GET['lId'])) {
			Template::addBreadcrumb('todos.php', 'Todos');
			Template::addBreadcrumb('projects.php?lId='.$_GET['lId'], Template::cutString($project->getTitle(), 20));
			$menu_selected = 2;		
		} else Template::addBreadcrumb('projects.php', 'Projekte');
		
		$content->addValue('id', $project->getId());
		$content->addValue('title', $project->getTitle());
		$content->addValue('text', nl2br($project->getDescription()));
		$content->addValue('todoCount', ($project->getTodoCount()==0) ? 'Keine' : $project->getTodoCount());
		$content->addValue('messageCount', ($project->getMessageCount()==0) ? 'Keine' : $project->getMessageCount());
		$content->addValue('todo_on_schedule', ($project->getTodoOnSchedule()=='') ? '0':$project->getTodoOnSchedule());
		$content->addValue('todo_behind_schedule', ($project->getTodoBehindSchedule()=='') ? '0':$project->getTodoBehindSchedule());
		$content->addValue('todo_waiting', ($project->getTodoWaiting()=='') ? '0':$project->getTodoWaiting());
		$content->addValue('todo_finished', ($project->getTodoFinished()=='') ? '0':$project->getTodoFinished());
		$content->addValue('todo_new', ($project->getTodoNew()=='') ? '0':$project->getTodoNew());
		
		$public = (isset($_GET['id'])) ? 'pId' : 'lId';
		$i=0;
		if($project->getTodoCount() > 0){
			foreach($project->getTodos() as $td){
				$tds = new SubViewDescriptor('todos');
				$todo_s = new SubViewDescriptor('todo_scripts');
				//print_r($td);
				$todo_s->addValue('id', $td->getId());
			
				$tds->addValue('title', $td->getTitle());
				$tds->addValue('p_id', $project->getId());
				$tds->addValue('id', $td->getId());
				$tds->addValue('status', $td->getStatus());
				$tds->addValue('status_img', str_replace(' ', '_', $td->getStatus()));
				$tds->addValue('target_date', $td->getTargetDate());
				$tds->addValue('public', $public);
				$tds->addValue('projected_hours', $td->getProjectedHours());
				
				$content->addSubView($tds);
				$content->addSubView($todo_s);
				
				unset($tds);
				unset($todo_s);
			}$content->removeSubView('no_todos');
		} else {
			$content->removeSubView('todos');
			$nm = new SubViewDescriptor('no_todos');
			$content->addSubView($nm);
		}
		
		$allmessages = -1;
		
		$msgs = $GLOBALS['Db-I']->getMessagesForList($project->getId(), 0, PROJECT_NEW_MESSAGES_COUNT);
		if($msgs != array()){
			foreach($msgs as $msg){
				$m = new SubViewDescriptor('messages');
				if($allmessages == -1) $allmessages = $msg->getAllMsgCount();
				
				$m->addValue('id', $msg->getId());
				$m->addValue('lId', $project->getId());
				$m->addValue('title', $msg->getTitle());
				$m->addValue('date', $msg->getDate());
				$m->addValue('u_id', $msg->getAuthor()->getId());
				$m->addValue('u_name', $msg->getAuthor()->getName());
				$m->addValue('text', $msg->getText());
				$m->addValue('reply_count', $msg->getReplyCount());
				
				$content->addSubView($m);
				unset($m);
			}
			$content->removeSubView('no_msgs');
		} else {
			$content->removeSubView('messages');
			$nm = new SubViewDescriptor('no_msgs');
			$content->addSubView($nm);
		}
		
		$content->addValue('msg_count', (($allmessages==0) || ($allmessages==-1)) ? 'Keine': $allmessages);
		//$content->removeSubView('messages');
		//TODO: Get all Messages for Project
		
	} else if(isset($_GET['action']) && $_GET['action']=='new'){
		$content = new ViewDescriptor('content/projects_new');
		
		if(isset($_GET['private'])){ //set subview for lId if project should be private
			$l = new SubViewDescriptor('private');
			$content->addSubView($l);
			unset($l);
			$content->addValue('title', 'Neue Liste');
		} else {
			$content->removeSubView('private');
			$content->addValue('title', 'Neues Projekt');
		}
		if(isset($_GET['id'])) Template::addBreadcrumb('projects.php?action=new', 'Neues Projekt');
		else Template::addBreadcrumb('projects.php?action=new&amp;private', 'Neue Liste');
		
	} else if(isset($_GET['action']) && $_GET['action']=='edit' && ((isset($_GET['id']) && $_GET['id'] != '') || (isset($_GET['lId']) && $_GET['lId'] != ''))){	//edit Project/List
		$action = ($_GET['action']);

		$id = (isset($_GET['id'])) ? $_GET['id'] : -1;
		$id = (isset($_GET['lId'])) ? $_GET['lId'] : $id;

		$project = $GLOBALS['Db-I']->getProject(($id));
		
		if(is_array($project) && isset($project['Error']) && $newid['Error'] == ERROR_NOT_ALLOWED){
			header('Location: projects.php?msg=no_rights');
			break;
		} 
		
		if(isset($_GET['id'])) { //--------- Breadcrumbs for Project or Todo (depends on Referrer)
			Template::addBreadcrumb('projects.php', 'Projekte');
			Template::addBreadcrumb('projects.php?id='.$id, Template::cutString($project->getTitle(), 20));	
			Template::addBreadcrumb('projects.php?id='.$id.'&amp;action=edit', 'bearbeiten');	
		} else if(isset($_GET['lId'])) {
			Template::addBreadcrumb('todos.php', 'Todos');
			Template::addBreadcrumb('projects.php?lId='.$_GET['lId'], Template::cutString($project->getTitle(), 20));		
			Template::addBreadcrumb('projects.php?id='.$id.'&amp;action=edit', 'bearbeiten');	
			$menu_selected = 2;
		} else Template::addBreadcrumb('projects.php', 'Projekte');
		
		$content = new ViewDescriptor('content/projects_edit');

		$content->addValue('status', ($project->getStatus()==Project::STATUS_PUBLIC) ? 'public':'private');
		$content->addValue('status_text', ($project->getStatus()==Project::STATUS_PUBLIC) ? '&Ouml;ffentlich':'Privat');
		$content->addValue('id', $project->getId());
		$content->addValue('title', $project->getTitle());
		$content->addValue('text', $project->getDescription());
		$content->addValue('todoCount', $project->getTodoCount());
		$content->addValue('messageCount', $project->getMessageCount());
		if(isset($_GET['lId'])){ //set subview for lId if project should be private
			$l = new SubViewDescriptor('lID');
			$content->addSubView($l);
			unset($l);
		} else $content->removeSubView('lID');
		
	} else {
		// Get All Projects
		$content = new ViewDescriptor('content/projects');
		
		$page = isset($_GET['page']) ? $_GET['page'] : 1;
		$pp = PROJECTS_PER_PAGE;
		$count_all = 0;
		
		$projects = $GLOBALS['Db-I']->getProjects(-1, ($page-1)*$pp, $pp, true); // no limit + public = true
		if(is_array($projects) && count($projects) >0){
			foreach($projects as &$project){
				$count_all = $project->getListCount();
				$pSV = new SubViewDescriptor('projects');
				
				if($project->getOwner()->getId() == $_SESSION['User']['id'] || $_SESSION['User']['group']=='admin'){
					$a = new SubViewDescriptor('authorized');
					$a->addValue('id', $project->getId());
					$pSV->addSubView($a);
				} else $pSV->removeSubView('authorized');
				
				$pSV->addValue('todo_finished', $project->getTodoFinished());
				$pSV->addValue('todo_on_schedule', $project->getTodoOnSchedule());
				$pSV->addValue('todo_behind_schedule', $project->getTodoBehindSchedule());
				$pSV->addValue('todo_waiting', $project->getTodoWaiting());
				$pSV->addValue('todo_new', $project->getTodoNew());
	
				$pSV->addValue('todo_count', $project->getTodoCount());
				$pSV->addValue('last_todo_date', $project->getLastTodoDate());
				$pSV->addValue('id', $project->getId());
				$pSV->addValue('title', $project->getTitle());
				$pSV->addValue('text', $project->getDescription());
				
				$content->addSubview($pSV);
				unset($pSV);
				
			}
		} else $content->removeSubView('projects');
		$content->addValue('pagina', Template::getPagina($page, $pp, $count_all, 'projects.php?page={@pp:page}'));
	}
		
	/* ========   NORMAL STUFF   ========= */
	// Messages
	if(isset($_GET['msg']) && isset($errors) && is_array($errors) && isset($error_class) && is_array($error_class)){
    	$get_msg = explode('|', $_GET['msg']);
    	foreach($get_msg as $error){
    		if(isset($errors[$error]) && isset($error[$GLOBALS['Localization']['language']])){
    			$GLOBALS['Messages'][] = '<span class="msg_'.$error_class[$error].'">'.$errors[$error].'</span>';
    		}
    	}
    }
    // render Main Template
	Template::generateMenu($main, $menu_selected);
	Template::renderBreadCrumb($main);
	$main->addValue('messages', implode("\n", $GLOBALS['Messages']));
	$main->addValue('content', $content->render());
	$main->addValue('script', '<script type="text/javascript" src="'.$GLOBALS['tpl']['root'].'_template/todolist/'.$GLOBALS['Localization']['language'].'/js/projects.js"></script>');
	$main->addValue('style', '<link rel="stylesheet" href="'.$GLOBALS['tpl']['root'].'_template/todolist/'.$GLOBALS['Localization']['language'].'/css/projekte.css" type="text/css"  media="screen"/>'.
	'<link rel="stylesheet" href="'.$GLOBALS['tpl']['root'].'_template/todolist/'.$GLOBALS['Localization']['language'].'/css/todo.css" type="text/css"  media="screen"/>');
	
	echo $main->render(); 
?>